import {request} from "~/utils/common/request.js"
const base_url = '/api/v1.0/file_manage'

// 获取文件列表
export const api_get_file_list = params => {
    return new Promise((resolve, reject) => {
        request.get(`${base_url}`, {params: params}).then(resp => {
            resolve(resp)
        }).catch(error => {
            reject(error)
        })
    })
}

// 删除文件
export const api_delete_files = params => {
    return new Promise((resolve, reject) => {
        request.patch(`/api/v1.0/base_info/sys_file/delete_files/`, {}, {params}).then(resp => {
            resolve(resp)
        }).catch(error => {
            reject(error)
        })
    })
}

// 下载文件
export const api_download_file = params => {
    return new Promise((resolve, reject) => {
        request.get(`${base_url}/${params.id}/download/`, {
            responseType: 'blob',
        }).then(resp => {
            const str = resp.headers['content-disposition']
            if (!resp || !str) {
                error(resp.message || '下载失败！')
                return
            }
            if (resp && resp.status === 200 && resp.data) {
                const { data, headers } = resp
                let fileName
                if (!params.file_name) {
                    // 切割出文件名
                    const fileNameEncode = resp.headers['content-disposition'].split('filename=')[1]
                    // 解码
                    fileName = decodeURIComponent(fileNameEncode)
                } else {
                    fileName = params.file_name
                }

                // if (headers['content-disposition']) {
                //   fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
                // } else {
                //   fileName = data.fileName
                // }
                // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
                const blob = new Blob([data], { type: headers['content-type'] })
                const dom = document.createElement('a')
                dom.href = window.URL.createObjectURL(blob)
                dom.download = decodeURIComponent(fileName)
                dom.style.display = 'none'
                document.body.appendChild(dom)
                dom.click()
                dom.parentNode.removeChild(dom)
                window.URL.revokeObjectURL(`${base_url}/${params.id}/download/`)
            } else {
                error(resp.message || '下载失败！')
            }
            resolve(resp)
        }).catch(error => {
            reject(error)
        })
    })
}


// 上传文件
// export const api_upload_file = data => {
//     return new Promise((resolve, reject) => {
//         request.post(`/api/v1.0/base_info/common_api/upload_file/`, data).then(resp => {
//             resolve(resp)
//         }).catch(error => {
//             reject(error)
//         })
//     })
// }
